import { StorageTypeEnum } from 'src/interface';

class Storage {
  private storage: globalThis.Storage;
  private handleList: Map<string, (params: string) => any>;
  constructor(type: StorageTypeEnum = StorageTypeEnum.LOCAL) {
    this.storage = type === StorageTypeEnum.LOCAL ? window.localStorage : window.sessionStorage;
    this.handleList = new Map();
  }
  addHandler<T = any>(key: string, fn: (params: string) => T) {
    this.handleList.set(key, fn);
    return true;
  }
  get(key: string) {
    const result = this.storage.getItem(key);
    if (result) {
      if (this.handleList.has(key)) {
        const fn = this.handleList.get(key);
        return fn?.(result);
      }
      try {
        return typeof result === 'string' ? JSON.parse(result) : result;
      } catch (err) {
        console.log(err);
        return '';
      }
    }
    return null;
  }
  set(key: string, value: any) {
    this.storage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value));
    return true;
  }
  remove(key: string) {
    this.storage.removeItem(key);
    return this.handleList.delete(key);
  }
  clear() {
    this.storage.clear();
    this.handleList.clear();
    return true;
  }
}

const storage = new Storage();

export { storage, Storage };
